package com.uzai.console.service.contract.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.contract.ContractSignDto;
import com.uzai.console.dto.contract.ContractSignPageVo;
import com.uzai.console.dto.contract.ContractSignQuery;
import com.uzai.console.entity.SysContract;
import com.uzai.console.entity.SysRole;
import com.uzai.console.enums.ContractStatusTypeEnum;
import com.uzai.console.enums.ContractTypeEnum;
import com.uzai.console.jsonvo.contract.ContractSignAddressJson;
import com.uzai.console.mapper.SysContractMapper;
import com.uzai.console.service.contract.SysContractService;
import com.uzai.console.service.feign.UzaiContractFeignService;
import com.uzai.console.service.feign.dto.ContractOpeDto;
import com.uzai.console.vo.contract.*;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.sysrole.SysRoleInfoVo;
import groovy.util.IFileNameFinder;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysContractServiceImpl implements SysContractService {

    @Autowired
    private SysContractMapper sysContractMapper;

    @Autowired
    private UzaiContractFeignService uzaiContractFeignService;

    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;



    @Override
    public ContractStatusVo getContractSignStatus(LoginVo loginVo) {
        ArrayList<SysContract> sysContract = sysContractMapper.selectByMerId(loginVo.getMerId());
        ContractStatusVo contractStatusVo = new ContractStatusVo();
        if (ObjectUtils.isEmpty(sysContract)) {
            contractStatusVo.setContractSignFlag(0);
            contractStatusVo.setContractSigningFlag(0);
            return contractStatusVo;
        }

        List<SysContract> completeContract = sysContract.stream().filter(s -> ContractStatusTypeEnum.COMPLETE.getKey().equals(s.getStatus())).collect(Collectors.toList());
        List<SysContract> signingContract = sysContract.stream().filter(s -> ContractStatusTypeEnum.UNDER_SIGNATURE.getKey().equals(s.getStatus())).collect(Collectors.toList());
        contractStatusVo.setContractSignFlag(ObjectUtils.isNotEmpty(completeContract) ? 1 : 0);
        contractStatusVo.setContractSigningFlag(ObjectUtils.isNotEmpty(signingContract) ? signingContract.get(0).getStatus() : ObjectUtils.isNotEmpty(completeContract) ? completeContract.get(0).getStatus() : 0);

        return contractStatusVo;
    }

    @Override
    public ContractDownLoadInfoVo getContractDownLoadUrl(ContractSignDto contractSignDto) {
        SysContract sysContract = checkContractStatus(contractSignDto);
        ContractOpeDto contractOpeDto = new ContractOpeDto();
        contractOpeDto.setSignFlowId(sysContract.getSignFlowId());
        UzaiRespVo<ContractDownLoadVo> contractDownloadUrl = uzaiContractFeignService.getContractDownloadUrl(contractOpeDto);
        ContractDownLoadInfoVo contractAddressVo = new ContractDownLoadInfoVo();
        if (contractDownloadUrl.getCode() == 200 && contractDownloadUrl.getData() != null) {
            contractAddressVo = contractDownloadUrl.getData().getFiles().get(0);
        }
        return contractAddressVo;
    }

    @Override
    public ContractSignAddressJson getContractSignInfo(ContractSignDto contractSignDto) {
        SysContract sysContract = sysContractMapper.selectById(contractSignDto.getId(), contractSignDto.getMerId());
        if (sysContract ==null ) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "当前合同不存在！");
        }
        ContractSignAddressJson contractSignInfoVo = new ContractSignAddressJson();
        if (sysContract.getSignUrl() != null) {
            contractSignInfoVo.setUrl(sysContract.getSignUrl());
            return contractSignInfoVo;
        }
        ContractOpeDto contractOpeDto = new ContractOpeDto();
        contractOpeDto.setSignFlowId(sysContract.getSignFlowId());
        UzaiRespVo<ContractSignAddressJson> contractInfo = uzaiContractFeignService.getContractSignUrl(contractOpeDto);

        if (contractInfo.getCode() == 200 && contractInfo.getData() != null) {
            contractSignInfoVo = contractInfo.getData();
        }
        return contractSignInfoVo;
    }

    /**
     * 检查合同是否签约完成
     * @param contractSignDto
     * @return
     */
    private SysContract checkContractStatus(ContractSignDto contractSignDto) {
        SysContract sysContract = sysContractMapper.selectById(contractSignDto.getId(), contractSignDto.getMerId());
        if (sysContract ==null ) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "当前合同不存在！");
        }
        if (!ContractStatusTypeEnum.COMPLETE.getKey().equals(sysContract.getStatus())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "签署成功状态才能下载！");
        }
        return sysContract;
    }

    @Override
    public Page<ContractSignPageVo> findContractSignBalList(ContractSignQuery contractSignQuery) {
        //新建返回到页面的LIST对象
        List<ContractSignPageVo> contractSignPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<SysContract> page = new Page<>();
        contractSignQuery.convert(page);
        contractSignQuery.setStatus(ContractStatusTypeEnum.COMPLETE.getKey());
        ArrayList<SysContract> sysContractArrayList = sysContractMapper.findByList(page, contractSignQuery);
        if (sysContractArrayList != null && sysContractArrayList.size() > 0) {
            for (SysContract sysContract : sysContractArrayList) {
                ContractSignPageVo contractSignPageVo = new ContractSignPageVo();
                BeanUtils.copyProperties(sysContract, contractSignPageVo);
                contractSignPageVo.setContractTypeName(ContractTypeEnum.getById(contractSignPageVo.getContractType()).getDesc());
                contractSignPageVo.setStatusName(ContractStatusTypeEnum.getById(contractSignPageVo.getStatus()).getDesc());
                contractSignPageVoList.add(contractSignPageVo);
            }
        }

        //返回到页面分页对象
        Page<ContractSignPageVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(contractSignPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    @Override
    public void updateContractAndReturn(String signFlowId, HttpServletResponse response) throws IOException {
        String contractSignSuccessUrl = uzaiConsoleSysConfig.getContractSignSuccessUrl();
        String contractSignFailUrl = uzaiConsoleSysConfig.getContractSignFailUrl();
        ContractOpeDto contractOpeDto = new ContractOpeDto();
        contractOpeDto.setSignFlowId(signFlowId);
        UzaiRespVo<ContractSignInfoVo> voUzaiRespVo = uzaiContractFeignService.getContractInfo(contractOpeDto);
        if (voUzaiRespVo.getCode() != 200 && voUzaiRespVo.getData() == null) {
            response.sendRedirect(contractSignFailUrl + URLEncoder.encode("签约失败，请重试","UTF-8"));
        }
        ContractSignInfoVo signInfoVo = voUzaiRespVo.getData();

        // 更新合同状态
        sysContractMapper.updateBySingFlowId(signFlowId, signInfoVo.getStatus());
        if (ContractStatusTypeEnum.VISA_REJECTION.getKey().equals(signInfoVo.getStatus())) {
            response.sendRedirect(contractSignFailUrl + URLEncoder.encode(ContractStatusTypeEnum.getById(signInfoVo.getStatus()).getDesc(),"UTF-8"));
        } else {
            response.sendRedirect(contractSignSuccessUrl + URLEncoder.encode("成功！","UTF-8"));
        }
    }
}
